package com.firesys.gridview;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.firesys.R;
import com.firesys.dbhelper.SharedPreferenceUtil;
import com.firesys.dbhelper.XmlNameHelper;
import com.firesys.povo.ResourcesPoVo;
import com.firesys.util.DateUtil;
import com.firesys.util.FileNameUtil;





import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;



/**
 * 图片显示
 * 
 * @author king
 * 
 */
public class ImageSwitcherActivity extends Activity implements OnItemSelectedListener, ViewFactory {
    public static final int ITEM0 = Menu.FIRST;// 系统值
    private static final int REQUEST_CODE_TAKE_IMAGE = 1;
    private ImageSwitcher imgsw;

    private Gallery gallery;

    private List<ResourcesPoVo> mThumbIds = null;

    private Context mContext;

    private String otherid = null;
    private String status = null;
    private String waterlistid;

    public boolean b = false;

    public int poston;// 当前位置

    public String imagepath;

    public String classname;
    public GridViewDao dao;
    public SharedPreferenceUtil sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);

	requestWindowFeature(Window.FEATURE_NO_TITLE);
	setContentView(R.layout.image_switcher_activity);
	imgsw = (ImageSwitcher) findViewById(R.id.imgswch1);
	gallery = (Gallery) findViewById(R.id.gallery);
	sp=new SharedPreferenceUtil(this);
         dao=new GridViewDao(this,sp.getValue(XmlNameHelper.SqliteName));
	Intent intent = getIntent();
	Bundle bundle = intent.getExtras();

	otherid = bundle.getString("otherid");

	status = bundle.getString("status");	
	
	waterlistid=bundle.getString("devicelistid");
	
	

	mThumbIds = dao.queryResour(otherid, status,waterlistid);
	init();
	if (mThumbIds == null || mThumbIds.size() < 1) {

	    Photograph();
	}
	
    }

    @Override
    /**
     * ʵ�ֵ�ViewFactory�ӿ�
     */
    public View makeView() {
	ImageView i = new ImageView(this);
	i.setBackgroundColor(0xFF000000);
	i.setScaleType(ImageView.ScaleType.FIT_CENTER);
	
	i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
	return i;

    }

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

	if (b) {
	    imgsw.setImageResource(mThumbIds.get(0).getId());
	} else {

	    Uri uri = Uri.parse(mThumbIds.get(arg2).getPath());
	    imgsw.setImageURI(uri);
	}

	poston = arg2;

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
	// TODO Auto-generated method stub

    }

    public class ImageAdapter extends BaseAdapter {
	public ImageAdapter(Context c) {
	    mContext = c;
	}

	@Override
	public int getCount() {

	    if (b) {

		return 1;
	    }
	    return mThumbIds.size();

	}

	@Override
	public Object getItem(int position) {

	    return position;
	}

	@Override
	public long getItemId(int position) {

	    return position;
	}

	@Override
	/**
	 * ���ImageView
	 */
	public View getView(int position, View convertView, ViewGroup parent) {

	    ImageView i = new ImageView(mContext);
	    if (b) {
		i.setImageResource(mThumbIds.get(0).getId());
	    } else {
		FileInputStream f;
		try {
		    f = new FileInputStream(mThumbIds.get(position).getPath());
		    FileDescriptor fd = f.getFD();

		    BitmapFactory.Options options = new BitmapFactory.Options();
		    options.inJustDecodeBounds = true;
		    BitmapFactory.decodeFileDescriptor(fd, null, options);

		    options.inSampleSize = BitmapUtil.computeSampleSize(options, 80, 128 * 128);

		    options.inJustDecodeBounds = false;
		    Bitmap bm = BitmapFactory.decodeStream(f, null, options);

		    // Bitmap firstBitmap =
		    // BitmapFactory.decodeFile(imagepath.get(position));
		    i.setImageBitmap(bm);
		} catch (FileNotFoundException e) {

		    e.printStackTrace();
		} catch (IOException e) {

		    e.printStackTrace();
		}

	    }
	    // i.setImageResource(mThumbIds[position]);//ͼƬԴ

	    i.setAdjustViewBounds(true);
	    i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));// ͼƬ��С
	    if (b)
		i.setBackgroundResource(R.drawable.contraband);// ͼƬ����
	    return i;
	}

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	menu.add(0, ITEM0, 0, "拍照");
	menu.add(0, ITEM0 + 1, 0, "删除");
	menu.findItem(ITEM0 + 1);

	return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
	if (item.getItemId() == ITEM0) {
	    Photograph();
	} else if (item.getItemId() == ITEM0 + 1) {
	    if(mThumbIds.size()==1){
		Toast.makeText(ImageSwitcherActivity.this, "至少要有一张照片", Toast.LENGTH_SHORT);
		return true;
	    }
	    delect();
	}
	return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	
	if (requestCode == REQUEST_CODE_TAKE_IMAGE) {
	    if (resultCode == RESULT_OK) {
		File f = new File(imagepath);
		if (f.exists()) {		 
		    dao.insertImage(otherid, imagepath, status,waterlistid);
		    mThumbIds = dao.queryResour(otherid, status,waterlistid);		 
		    b = false;
		    FileInputStream fis = null;
		    try {
			fis = new FileInputStream(imagepath);
			FileDescriptor fd = fis.getFD();
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFileDescriptor(fd, null, options);
			  int outWidth = Math.round(options.outWidth/800);
			    int outHeight =Math.round( options.outHeight/600);
			    
			     if(outWidth>1&&outHeight>1){
				 if(outHeight>=outWidth){
				     options.inSampleSize=outWidth;
				 }else{
				     options.inSampleSize=outHeight;
				 }
			     }else{
				 options.inSampleSize=1;
			     }			
			     int degree =readPictureDegree( f.getAbsolutePath());
			options.inJustDecodeBounds = false;
			Bitmap mbitmap = BitmapFactory.decodeStream(fis, null, options);
			//无法 解释为什么当旋转角度为0是会报错，必须要用Copy方法
		        if(degree==0){
		            mbitmap=mbitmap.copy(Bitmap.Config.ARGB_8888, true);
		        }else{	           
		            Matrix matrix = new Matrix();
			     matrix.reset();
			    //设置图片旋转角度
			     matrix.postRotate(degree);
				// 创建新的图片			
			      mbitmap = Bitmap.createBitmap(mbitmap, 0, 0, mbitmap.getWidth(), mbitmap.getHeight(), matrix, true);			 
		        }
			
			FileOutputStream out = new FileOutputStream(imagepath);
			Canvas canvas = new Canvas(mbitmap);
			TextPaint paint = new TextPaint();
			paint.setTextSize(20);
			paint.setColor(Color.RED);
			canvas.drawText(DateUtil.getNowDate(), mbitmap.getWidth()-190, 30f, paint);
			canvas.save();
			mbitmap.compress(Bitmap.CompressFormat.JPEG, 50, out);
			out.flush();
			out.close();
		    } catch (FileNotFoundException e) {
			
			e.printStackTrace();
		    } catch (IOException e) {
			
			e.printStackTrace();
		    }
		}

		init();
	    }else if (resultCode == RESULT_CANCELED) {		
		File f=new File(imagepath);
		
		
		   if((mThumbIds==null||mThumbIds.size()<1)&&!f.exists()){
		   
		       mThumbIds = new ArrayList<ResourcesPoVo>();
			    ResourcesPoVo resour = new ResourcesPoVo();
			    resour.setId(R.drawable.contraband);
			    mThumbIds.add(resour);
			    b = true;
			  
		   }else if(mThumbIds.size()==1&&!f.exists()){
		    
		       if(mThumbIds.get(0).getOtherid()>0){			  
			    b = false; 
		       }else{
			   b = true;
			 
		       }
		   }else{
		    
		       b=false;
		     
		   }
		  init();
		}else if(resultCode==RESULT_FIRST_USER){
		    
		}

	} 

	super.onActivityResult(requestCode, resultCode, data);
    }

   
    /**
     * 初始化
     */
    public void init() {
	imgsw.removeAllViews();
	imgsw.setFactory(this);
	imgsw.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
	imgsw.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
	gallery.setAdapter(new ImageAdapter(this));
	gallery.setOnItemSelectedListener(this);
    }

    /**
     * 删除一张照片
     */
    public void delect() {
	if (b) {
	    Toast.makeText(this, "没有图片不能进行此操作", Toast.LENGTH_LONG).show();
	    return;
	}
	
	boolean bb = dao.delectOne(mThumbIds.get(poston).getId() + "",status);
	File file = new File(mThumbIds.get(poston).getPath());
	file.delete();
	mThumbIds = dao.queryResour(otherid, status,waterlistid);
	
	if (mThumbIds == null | mThumbIds.size() < 1) {
	    mThumbIds = new ArrayList<ResourcesPoVo>();
	    ResourcesPoVo resour = new ResourcesPoVo();
	    resour.setId(R.drawable.contraband);
	    mThumbIds.add(resour);
	    b = true;

	}
	init();
	if (bb) {
	    Toast.makeText(this, "删除成功", Toast.LENGTH_LONG).show();
	} else {
	    Toast.makeText(this, "删除失败", Toast.LENGTH_LONG).show();
	}
    }

    // 拍照
    public void Photograph() {

	if (otherid == null | otherid.trim().equals("")) {
	    Toast.makeText(ImageSwitcherActivity.this, "没有水表不能使用此功能", Toast.LENGTH_LONG).show();
	    return;
	}

	Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	FileNameUtil f = new FileNameUtil();
	if(status.equals("1")){
	    imagepath=sp.getValue(XmlNameHelper.userID)+"/routdeviceimg/"+waterlistid;
	}else if(status.equals("2")){
	    imagepath=sp.getValue(XmlNameHelper.userID)+"/maintainimg/"+waterlistid;
	}else if(status.equals("3")){
	    imagepath=sp.getValue(XmlNameHelper.userID)+"/repairimg/"+waterlistid;
	}else if(status.equals("4")){
	    imagepath=sp.getValue(XmlNameHelper.userID)+"/rushrepair/"+waterlistid;
	}else if(status.equals("-1")){
	    imagepath="order/img";
	}
	
	imagepath=f.SDCardPath(imagepath);

	if (imagepath == null) {
	    Toast.makeText(this, "SD卡不可用", Toast.LENGTH_LONG).show();
	    return;
	}
	String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg";
	imagepath = imagepath + "/" + sp.getValue(XmlNameHelper.userID)+fileName;
	intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(imagepath)));
	startActivityForResult(intent, REQUEST_CODE_TAKE_IMAGE);
    }

    @Override
    protected void onDestroy() {
	dao.close();
	super.onDestroy();
    }

    /**
     * 读取图片属性：旋转的角度
     * 
     * @param path
     *            图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
	int degree = 0;
	try {
	    ExifInterface exifInterface = new ExifInterface(path);
	    int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
	    switch (orientation) {
	    case ExifInterface.ORIENTATION_ROTATE_90:
		degree = 90;
		break;
	    case ExifInterface.ORIENTATION_ROTATE_180:
		degree = 180;
		break;
	    case ExifInterface.ORIENTATION_ROTATE_270:
		degree = 270;
		break;
	    }
	} catch (IOException e) {
	    e.printStackTrace();
	}
	return degree;
    }
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
	  if(keyCode==KeyEvent.KEYCODE_BACK){
	      Intent intent=new Intent();
	   List<ResourcesPoVo> list= dao.queryResour(otherid, status,waterlistid);
	   if(list!=null&&list.size()>0){
	   
	     setResult(RESULT_OK, intent);
	   }else{
	     setResult(RESULT_CANCELED, intent);
	   }
	   finish();
	      return false;
	  }
	return super.onKeyUp(keyCode, event);
    }
    
    
}
